package org.sninwo.lnbook.book.web;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.struts2.convention.annotation.Namespace;
import org.sninwo.lnbook.base.BaseAction;
import org.sninwo.lnbook.book.entity.BookType;
import org.sninwo.lnbook.book.service.BookManager;
import org.sninwo.lnbook.uitls.LnBookUtils;

@Namespace("/admin")
public class BookTypeAction extends BaseAction {
	private static final long serialVersionUID = -6064957390811877985L;
	public BookType bookType = new BookType();
	public long bookTypeId;
	
	@Resource BookManager bookMgr;
	
	public String save(){
		bookMgr.saveBookType(bookType);
		return successJson(bookType);
	}
	
	public String remove(){
		if (bookMgr.getBookCount(bookTypeId) > 0){
			LnBookUtils.throwError("该类别还有书籍，先删除这些书籍才能删除类别");
		}
		bookMgr.removeBookType(bookTypeId);
		return successJson();
	}
	
	public String get(){
		if (bookTypeId == 0){
			int seq = bookMgr.getMaxSeqOfBookType() + 1;
			BookType bookType = new BookType();
			bookType.setSeq(seq);
			return json(bookType);
		}
		BookType bt = bookMgr.getBookType(bookTypeId);
		return json(bt);
	}
	
	public String getAllBookTypes(){
		List<Map<String, Object>> bookTypes = new ArrayList<Map<String, Object>>();
		for (BookType type : bookMgr.getAllBookTypes()){
			Map<String, Object> map = new HashMap<String, Object>(2);
			map.put("id", type.getId());
			map.put("text", type.getName());
			map.put("leaf", true);
			bookTypes.add(map);
		}
		return json(bookTypes);
	}
}
